﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using CommonManage = DevelopStudio.Common.Manage;
using System.IO;
using SNSHelper.Common;


namespace DevelopStudio.Common.Basic
{
    [Serializable]
    [XmlRoot("Root")]
    public class DSFileDiffInfo
    {
        [XmlElement("LocalDiff")]
        public bool LocalDiff { get; set; }

        [XmlElement("WorkingCopyPath")]
        public string WorkingCopyPath { get; set; }

        [XmlArray("DiffInfos")]
        [XmlArrayItem("DiffInfo", typeof(DSFileDiffUnitInfo))]
        public List<DSFileDiffUnitInfo> DiffInfos { get; set; }

        public static DSFileDiffInfo ParseToInstance(string path)
        {
            string tempselfPath = string.Empty;

            if (Path.GetExtension(path) != AppConst.DiffToolFileSuffix)
            {
                return null;
            }

            tempselfPath = CommonManage.Utility.GetDiffTempFullFileName(AppConst.DSFileDiffInfoFileKey, 0);
            Dictionary<string, string> unZipFiles = new Dictionary<string, string>();
            unZipFiles.Add(AppConst.DSFileDiffInfoFileKey, tempselfPath);
            UnZip.UnZipFiles(unZipFiles, path);

            return CommonManage.Utility.SerializedFile2Object<DSFileDiffInfo>(tempselfPath);
        }

        public bool Pack(string path)
        {
            if (Path.GetExtension(path) != AppConst.DiffToolFileSuffix)
            {
                return false;
            }

            string tempselfPath = CommonManage.Utility.GetStudioTempFullFileName(AppConst.DSFileDiffInfoFileKey, 0);

            CommonManage.Utility.SerializedObject2File(this, tempselfPath);
            Dictionary<string, string> zipFiles = new Dictionary<string, string>();
            zipFiles.Add(AppConst.DSFileDiffInfoFileKey, tempselfPath);

            if (this.LocalDiff == false)
            {
                foreach(DSFileDiffUnitInfo var in this.DiffInfos)
                {
                    if (string.IsNullOrEmpty(var.Left.Path) == false)
                    {
                        zipFiles.Add(var.Left.Key, var.Left.Path);
                    }

                    if (string.IsNullOrEmpty(var.Right.Path) == false)
                    {
                        zipFiles.Add(var.Right.Key, var.Right.Path);
                    }
                }
            }

            Zip.ZipFileList(zipFiles, path);

            foreach (KeyValuePair<string, string> var in zipFiles)
            {
                try
                {
                    if (var.Value.StartsWith(CommonManage.Utility.TempStudioPath) == true)
                    {
                        File.Delete(var.Value);
                    }
                }
                catch (Exception)
                {
                }
            }

            return true;
        }
    }
}
